# -*- coding: utf-8 -*-
import sys
sys.path.append('../..')
from db.mysql import MysqlClient
import asyncio, aiohttp
import json
from common.helper import Helper
from common.config import *
from itertools import product


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "乐享人生保障（成人男性版）保险"

    def genProductInfo(self):
        plan = {
            "planA": {
                "year": ["18-20","21-25","26-30","31-35","36-40","41-45","46-50","51-55"],
                "days": ["1y"],
                "people_count": ["1"],
                "accident_death": ["10000"],
                "accident_medical": ["5000"],
                "serious_disable": ["100000"],
                "cancer_medical": ["100000"],
                "myselfDriver": ["50000"],
                "accident_hospital": ["100/天"],
                "serious_allowance": ["200/天"],
                "airplane_death": ["300000"],
                "train_death": ["100000"],
                "ship_death": ["100000"],
                "taxi_death": ["50000"],
                "exigency_back": ["100000"],
                "public_duty": ["100000"],

            },
            "planB": {
                "year": ["18-20","21-25","26-30","31-35","36-40","41-45","46-50","51-55"],
                "days": ["1y"],
                "people_count": ["1"],
                "accident_death": ["20000"],
                "accident_medical": ["10000"],
                "serious_disable": ["200000"],
                "cancer_medical": ["200000"],
                "myselfDriver": ["100000"],
                "accident_hospital": ["100/天"],
                "serious_allowance": ["200/天"],
                "airplane_death": ["600000"],
                "train_death": ["200000"],
                "ship_death": ["100000"],
                "taxi_death": ["50000"],
                "exigency_back": ["200000"],
                "public_duty": ["200000"],

            }

        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["days"], plan[k]["people_count"], plan[k]["accident_death"],
                             plan[k]["accident_medical"], plan[k]["serious_disable"], plan[k]["cancer_medical"],
                             plan[k]["myselfDriver"], plan[k]["accident_hospital"], plan[k]["serious_allowance"],
                             plan[k]["airplane_death"], plan[k]["train_death"], plan[k]["ship_death"],
                             plan[k]["taxi_death"],
                             plan[k]["exigency_back"], plan[k]["public_duty"]):
                data = Helper.formatProductInfo(plan[k], v)
                yield data

    async def requestJson(self, data):
        year = data["year"].split("-")
        params = {"ageLimit": {"ageTo": year[0], "ageFrom": year[1]}, "dayLimit": {"dayTo": "366", "dayFrom": "366"},
                  "planCode": "CIYOUMAP1" if data["accident_death"] == "10000" else "CIYOUMAP2", "planName": "计划一" if data["accident_death"] == "10000" else "计划二", "productCode": "HET-ADULT-M", "productName": "乐享人生-男性版",
                  "day": "366"}

        payload = json.dumps( params,ensure_ascii=False )
        async with aiohttp.ClientSession() as session:
            async with session.post( domain[self.name]["url"],headers=domain[self.name]["header"],data=payload) as resp:
                res = await resp.text()
                price  = Helper.decimalParse(  json.loads( res  )["premium"] )
                rec = {
                    "name":self.name,
                    "company":"京东安联",
                    "price":price
                }
                rec.update( data )
                Helper.mergeTable( self.name,self.mysql,rec )



    def asyncTask(self):
        tasks = [
            self.requestJson(data) for data in self.genProductInfo()

        ]
        event_loop = asyncio.get_event_loop()
        event_loop.run_until_complete(asyncio.gather(*tasks))

